import { login } from '../../api/user'

const userModule = {
  state: {
    username: '',
    nickname: '',
    avatarUrl: '',
    token: ''
  },
  mutations: {
    LOGIN_SUCCESS (state, payload) {
      const { username, nickname, avatarUrl, token } = payload
      state.username = username
      state.nickname = nickname
      state.avatarUrl = avatarUrl
      state.token = token
    },
    LOGOUT_SUCCESS (state) {
      state.username = ''
      state.nickname = ''
      state.avatarUrl = ''
      state.token = ''
    }
  },
  actions: {
    /**
     * 用户异步登录的 action
     * @param {*} store 与 store 对象结构一致
     * @param {*} payload 用户登录时传递的用户名与密码
     */
    loginAsync (store, payload) {
      return login(payload)
        .then(data => {
          store.commit('LOGIN_SUCCESS', data)
          return { loginSuccess: true }
        })
        .catch(() => {})
    }
  }
}

export default userModule
